import { Context } from 'koa'
import {
  USERNAME_OR_PASSWORD_IS_REQUIRED,
  USERNAME_ALREADY_EXISTS,
  USER_DOES_NOT_EXISTS,
  PASSWORD_IS_INCORRECT,
  UNAUTHORIZED,
  ROLE_ALREADY_EXISTS,
  ROLE_NAME_IS_REQUIRE,
  PARAMS_IS_REQUIRED,
  ID_PARAMS_IS_REQUIRED,
  PERMISSION_ALREADY_EXISTS,
  PID_NOT_EXISTS,
  DEFAULE_ERROR
} from '../constants/error-types'

const defaultError = new Error(DEFAULE_ERROR)

/**
 * 固定错误
 * @param ctx
 * @param error
 */
const errorHandler = (ctx: Context, error: Error = defaultError): void => {
  let code: number, msg: string
  switch (error.message) {
    case USERNAME_OR_PASSWORD_IS_REQUIRED:
      code = 602
      msg = '用户名或密码不能为空'
      break

    case USERNAME_ALREADY_EXISTS:
      code = 409
      msg = '用户名已存在'
      break

    case USER_DOES_NOT_EXISTS:
      code = 403
      msg = '该用户未注册'
      break

    case PASSWORD_IS_INCORRECT:
      code = 403
      msg = '密码错误'
      break

    case UNAUTHORIZED:
      code = 401
      msg = '未授权'
      break

    case ROLE_ALREADY_EXISTS:
      code = 409
      msg = '该角色已存在'
      break

    case ROLE_NAME_IS_REQUIRE:
      code = 602
      msg = '角色信息不能为空'
      break

    case PARAMS_IS_REQUIRED:
      code = 602
      msg = '缺少xxx参数'
      break

    case ID_PARAMS_IS_REQUIRED:
      code = 602
      msg = 'id必传'
      break

    case PERMISSION_ALREADY_EXISTS:
      code = 201
      msg = '权限名称已存在'
      break

    case PID_NOT_EXISTS:
      code = 602
      msg = '未找到父权限数据，请重新选择'
      break

    case DEFAULE_ERROR:
      code = 602
      msg = '网络错误，请稍后重试'
      break

    default:
      code = 404
      msg = 'NOT FOUND'
  }
  ctx.body = {
    code,
    msg
  }
}

/**
 * 系统错误
 */
const systemErrorHandler = (ctx: Context, errMessage: string = '系统错误'): void => {
  ctx.body = {
    code: 80001,
    msg: errMessage
  }
}
export {
  errorHandler,
  systemErrorHandler
}